package com.cz.basetool;

import android.util.Log;

import com.cz.basetool.ui_work.util.log.AndroidConsoleLogPrinter;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 编码解码工具类
 *
 * @author Bitter
 */
public class CodeTool {
    private static final String TAG = "CodeTool";

    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    static final char CRC_TABLE_8408[] = { 0x0000, 0x1189, 0x2312, 0x329B,
            0x4624, 0x57AD, 0x6536, 0x74BF, 0x8C48, 0x9DC1, 0xAF5A, 0xBED3,
            0xCA6C, 0xDBE5, 0xE97E, 0xF8F7, 0x1081, 0x0108, 0x3393, 0x221A,
            0x56A5, 0x472C, 0x75B7, 0x643E, 0x9CC9, 0x8D40, 0xBFDB, 0xAE52,
            0xDAED, 0xCB64, 0xF9FF, 0xE876, 0x2102, 0x308B, 0x0210, 0x1399,
            0x6726, 0x76AF, 0x4434, 0x55BD, 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1,
            0xEB6E, 0xFAE7, 0xC87C, 0xD9F5, 0x3183, 0x200A, 0x1291, 0x0318,
            0x77A7, 0x662E, 0x54B5, 0x453C, 0xBDCB, 0xAC42, 0x9ED9, 0x8F50,
            0xFBEF, 0xEA66, 0xD8FD, 0xC974, 0x4204, 0x538D, 0x6116, 0x709F,
            0x0420, 0x15A9, 0x2732, 0x36BB, 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7,
            0x8868, 0x99E1, 0xAB7A, 0xBAF3, 0x5285, 0x430C, 0x7197, 0x601E,
            0x14A1, 0x0528, 0x37B3, 0x263A, 0xDECD, 0xCF44, 0xFDDF, 0xEC56,
            0x98E9, 0x8960, 0xBBFB, 0xAA72, 0x6306, 0x728F, 0x4014, 0x519D,
            0x2522, 0x34AB, 0x0630, 0x17B9, 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5,
            0xA96A, 0xB8E3, 0x8A78, 0x9BF1, 0x7387, 0x620E, 0x5095, 0x411C,
            0x35A3, 0x242A, 0x16B1, 0x0738, 0xFFCF, 0xEE46, 0xDCDD, 0xCD54,
            0xB9EB, 0xA862, 0x9AF9, 0x8B70, 0x8408, 0x9581, 0xA71A, 0xB693,
            0xC22C, 0xD3A5, 0xE13E, 0xF0B7, 0x0840, 0x19C9, 0x2B52, 0x3ADB,
            0x4E64, 0x5FED, 0x6D76, 0x7CFF, 0x9489, 0x8500, 0xB79B, 0xA612,
            0xD2AD, 0xC324, 0xF1BF, 0xE036, 0x18C1, 0x0948, 0x3BD3, 0x2A5A,
            0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E, 0xA50A, 0xB483, 0x8618, 0x9791,
            0xE32E, 0xF2A7, 0xC03C, 0xD1B5, 0x2942, 0x38CB, 0x0A50, 0x1BD9,
            0x6F66, 0x7EEF, 0x4C74, 0x5DFD, 0xB58B, 0xA402, 0x9699, 0x8710,
            0xF3AF, 0xE226, 0xD0BD, 0xC134, 0x39C3, 0x284A, 0x1AD1, 0x0B58,
            0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C, 0xC60C, 0xD785, 0xE51E, 0xF497,
            0x8028, 0x91A1, 0xA33A, 0xB2B3, 0x4A44, 0x5BCD, 0x6956, 0x78DF,
            0x0C60, 0x1DE9, 0x2F72, 0x3EFB, 0xD68D, 0xC704, 0xF59F, 0xE416,
            0x90A9, 0x8120, 0xB3BB, 0xA232, 0x5AC5, 0x4B4C, 0x79D7, 0x685E,
            0x1CE1, 0x0D68, 0x3FF3, 0x2E7A, 0xE70E, 0xF687, 0xC41C, 0xD595,
            0xA12A, 0xB0A3, 0x8238, 0x93B1, 0x6B46, 0x7ACF, 0x4854, 0x59DD,
            0x2D62, 0x3CEB, 0x0E70, 0x1FF9, 0xF78F, 0xE606, 0xD49D, 0xC514,
            0xB1AB, 0xA022, 0x92B9, 0x8330, 0x7BC7, 0x6A4E, 0x58D5, 0x495C,
            0x3DE3, 0x2C6A, 0x1EF1, 0x0F78 };



    /*static final char CRC_TABLE_8408[] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
            0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
            0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
            0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
            0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
            0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
            0x3653, 0x2672, 0x1611,  0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
            0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
            0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
            0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
            0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
            0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
            0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
            0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
            0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
            0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
            0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
            0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
            0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
            0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
            0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
            0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
            0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
            0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
            0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
            0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
            0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
            0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
            0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
            0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
            0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
            0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0};*/
    /**
     * 在字符串的前面加0
     *
     * @param str    原始数据
     * @param length 需要的字节的长度，例如("123",3)返回的结果为"000123"
     * @return 返回前面加0并且达到指定字节长度的字符串
     */
    public static String AddZeroToFront(String str, int length) {
        StringBuilder strbd;
        if (str == null) {
            strbd = new StringBuilder();
        } else {
            strbd = new StringBuilder(str);
        }
        for (int i = strbd.length(); i < length * 2; i++) {
            strbd.insert(0, 0);
        }
        return strbd.toString();
    }

    /**
     * 在字符串的后面加0
     *
     * @param str    原始数据
     * @param length 需要的字节的长度，例如("123",3)返回的结果为"123000"
     * @return 返回后面加0并且达到指定字节长度的字符串
     */
    public static String AddZeroToBehind(String str, int length) {
        StringBuilder strbd;
        if (str == null) {
            strbd = new StringBuilder();
        } else {
            strbd = new StringBuilder(str);
        }
        for (int i = strbd.length(); i < length * 2; i++) {
            strbd.append(0);
        }
        return strbd.toString();
    }

    /**
     * 异或方法，通过给出的字符串算出异或的值
     *
     * @param str 需要计算异或的字符串
     * @return 返回异或值
     */
    public static String XOR(String str) {
        if (str == null || str.length() % 2 != 0) {
            return "";
        }
        int xor = 0;
        int len = str.length() / 2;
        for (int i = 0; i < len; i++) {
            try {
                xor ^= Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return IntToHexString(xor);
    }

    /**
     * 异或方法，通过给出的字符串算出异或的值
     *
     * @param str   需要计算异或的字符串
     * @param start 从第多少个字节开始算异或
     * @return 返回异或值
     */
    public static String XOR(String str, int start) {
        if (str == null || str.length() % 2 != 0) {
            return "";
        }
        int xor = 0;
        int len = str.length() / 2;
        for (int i = start; i < len; i++) {
            try {
                xor ^= Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return IntToHexString(xor);
    }

    /**
     * 字符串变字符数组方法
     *
     * @param str 需要变成字符数组的字符串
     * @return 返回为两个字母为一个字符的数组
     */
    public static String[] StringToStringArray(String str) {
        if (str == null || str.length() % 2 != 0) {
            return new String[0];
        }
        int len = str.length() / 2;
        String[] strArr = new String[len];
        for (int i = 0; i < len; i++) {
            try {
                strArr[i] = str.substring(i * 2, i * 2 + 2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return strArr;
    }

    /**
     * 十六进制字符串到byte数组
     */
    public static byte[] HexToByteArr(String str) {
        String[] strArr = StringToStringArray(str);
        byte[] b = new byte[strArr.length];
        for (int i = 0; i < strArr.length; i++) {
            b[i] = (byte) Integer.parseInt(strArr[i], 16);
        }
        return b;
    }

    /**
     * byte字节到字符串
     */
    public static String ByteToHexString(byte dec) {
        return String.valueOf(DIGITS_UPPER[(0xF0 & dec) >>> 4])
                + String.valueOf(DIGITS_UPPER[dec & 0x0F]);
    }

    /**
     * byte字节到字符串
     */
    public static String IntToHexString(int dec) {
        return String.valueOf(DIGITS_UPPER[(0xF0 & dec) >>> 4])
                + String.valueOf(DIGITS_UPPER[dec & 0x0F]);
    }

    /**
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String StringToHexString(String str) {
        if (str.isEmpty()) return "";

        StringBuilder strbd = new StringBuilder();
        byte[] bytes = null;
        try {
            bytes = str.getBytes("GBK");
            for (int i = 0; i < bytes.length; i++)
                strbd.append(num2HexStr(bytes[i] & 0xff));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return strbd.toString().toUpperCase();
    }

    /**
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String StringToHexString(String str,int byteLen) {
        String result1 = StringToHexString(str);
        while (result1.length() < byteLen * 2){
            result1 = "0" + result1;
        }
        return result1;
    }


    /**
     * 将16进制数字编码成字符串,适用于所有字符（包括中文）
     */
    public static String HexStringToString(String str) {
        if (str.length() % 2 != 0) {
//            AndroidConsoleLogPrinter.e("cz", "HexStringToString: len为奇数");
            return "";
        }
        StringBuffer sb = new StringBuffer();
        String string = "";
        for (int i = 0; i < str.length(); i = i + 2) {
            sb.append("%").append(str.subSequence(i, i + 2));
        }
        try {
            string = URLDecoder.decode(sb.toString(), "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }


    /**
     * 将16进制数字编码成字符串,适用于所有字符（包括中文）去掉空格
     */
    public static String HexStringToString2(String data) {
        String str = delete00Str(data);
        if (str.length() % 2 != 0) {
//            AndroidConsoleLogPrinter.e("cz", "HexStringToString: len为奇数");
            return "";
        }
        StringBuffer sb = new StringBuffer();
        String string = "";
        for (int i = 0; i < str.length(); i = i + 2) {
            sb.append("%").append(str.subSequence(i, i + 2));
        }
        try {
            string = URLDecoder.decode(sb.toString(), "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }

    private static String delete00Str(String data){
        int point = 0;

        for (int i = 0 ; i < data.length() ;i = i+2){
            if ("00".equals(data.substring(i,i+2))){
                point = i;
                break;
            }
        }
        return  data.substring(0,point);
    }
    /**
     * 55AA0B->[0x55,0xAA,0x0B]
     */
    public static byte[] HexArr2byteArr(String value)
            throws NumberFormatException {
        int len = value.length() / 2;
        byte[] b = new byte[len];
        for (int i = 0; i < len; i++) {
            b[i] = (byte) ((int) Integer.valueOf(
                    value.substring(i * 2, i * 2 + 2), 16));
        }
        return b;
    }

    public static byte[] hexStr2ByteArr(String value)
            throws NumberFormatException {
        int len = value.length() / 2;
        byte[] b = new byte[len];
//        String s = "";
        for (int i = 0; i < len; i++) {
            b[i] = (byte) (Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16));
//            s = s + b[i] + ",";
        }
//        CZLogUtil.loge("---------->>> s = " + s);
        return b;
    }

    public static int[] hexStr2IntArr(String value)
            throws NumberFormatException {
        int len = value.length() / 2;
        int[] b = new int[len];
//        String s = "";
        for (int i = 0; i < len; i++) {
            b[i] =   (Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16));
//            s = s + b[i] + ",";
        }
//        CZLogUtil.loge("---------->>> s = " + s);
        return b;
    }


    /**
     * [0x55,0xAA,0x0B]->55AA0B
     */
    public static String ByteArrToHexArr(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp = "";
        for (int i = 0; i < bArray.length; i++) {
            try {
                sTemp = Integer.toHexString(0xFF & bArray[i]);
            } catch (Exception e) {
                System.err.println("bytesToHexString() bArray[" + i + "]="
                        + bArray[i]);
                e.printStackTrace();
            }
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static String ByteArrToHexArr(byte[] bArray, int length) {
        StringBuffer sb = new StringBuffer(length);
        String sTemp;
        for (int i = 0; i < length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }

        return sb.toString();
    }

    /**
     * 将字符串编码成16进制数字,适用于所有字符（包括中文-Unicode编码） “北京”转为“53174EAC”
     */
    public static String StringToUnicodeHexString(String str) {
        StringBuilder strbd = new StringBuilder();
        byte[] bytes = null;
        try {
            bytes = str.getBytes("Unicode");
            for (int i = 2; i < bytes.length; i++)
                strbd.append(AddZeroToFront(
                        Integer.toHexString(bytes[i] & 0xff), 1));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return strbd.toString().toUpperCase();
    }

    /**
     * 将16进制数字编码成字符串,适用于所有字符（包括中文-Unicode编码）“53174EAC”转为“北京”
     */
    public static String HexStringToUnicodeString(String str) {
        StringBuffer sb = new StringBuffer();
        String string = "";
        for (int i = 0; i < str.length(); i = i + 2) {
            sb.append("%").append(str.subSequence(i, i + 2));
        }
        try {
            string = URLDecoder.decode(sb.toString(), "Unicode");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }

    /**
     * 标识位：采用 0x7e 表示，若校验码、消息头以及消息体中出现 0x7e，则要 进行转义处理，转义规则定义如下：</br>
     * <p>
     * 0x7e <————> 0x7d 后紧跟一个 0x02；</br>
     * <p>
     * 0x7d <————> 0x7d 后紧跟一个 0x01；</br> 转义处理过程如下：</br>
     * 发送消息时：消息封装——>计算并填充校验码——>转义；</br> 接收消息时：转义还原——>验证校验码——>解析消息；</br>
     * 例：发送一包内容为 0x30 0x7e 0x08 0x7d 0x55 的数据包，则经过封装如下： 0x7e 0x30 7d 0x02 0x08
     * 0x7d 0x01 0x55 0x7e。
     *
     * @param str 要转义的消息包
     * @return 返回转义之后的完整单包发送的数据，返回为大写的完整消息
     */
    public static String getEnEscape7EString(String str) {
        StringBuilder strbd = new StringBuilder(str);
        String[] strArr = CodeTool.StringToStringArray(str.toUpperCase());
        for (int i = strArr.length - 2; i > 0; i--) {
            if ("7D".equals(strArr[i])) {
                strbd.replace(i * 2, (i + 1) * 2, "7D");
                strbd.insert((i + 1) * 2, "01");
            }
            if ("7E".equals(strArr[i])) {
                strbd.replace(i * 2, (i + 1) * 2, "7D");
                strbd.insert((i + 1) * 2, "02");
            }
        }
        return strbd.toString().toUpperCase();
    }


    /**
     * 标识位：采用 0x7e 表示，若校验码、消息头以及消息体中出现 0x7e，则要 进行转义处理，转义规则定义如下：</br>
     * <p>
     * 0x7e <————> 0x7d 后紧跟一个 0x02；</br>
     * <p>
     * 0x7d <————> 0x7d 后紧跟一个 0x01；</br> 转义处理过程如下：</br>
     * 发送消息时：消息封装——>计算并填充校验码——>转义；</br> 接收消息时：转义还原——>验证校验码——>解析消息；</br>
     * 例：发送一包内容为 0x30 0x7e 0x08 0x7d 0x55 的数据包，则经过封装如下： 0x7e 0x30 7d 0x02 0x08
     * 0x7d 0x01 0x55 0x7e。
     *
     * @param str 接收到的消息包
     * @return 返回转义之后的完整单包发送的数据，返回为大写的完整消息
     */
    public static String getDeEscape7EString(String str) {
        StringBuilder strbd = new StringBuilder(str);
        String[] strArr = CodeTool.StringToStringArray(str.toUpperCase());
        for (int i = strArr.length - 2; i >= 0; i--) {
            if ("7D01".equals(strArr[i] + strArr[i + 1])) {
                strbd.replace(i * 2, (i + 2) * 2, "7D");
            }
            if ("7D02".equals(strArr[i] + strArr[i + 1])) {
                strbd.replace(i * 2, (i + 2) * 2, "7E");
            }
        }
        return strbd.toString().toUpperCase();
    }

    public static String connectStrArray(String[] array, String connector) {
        String result = "";
        for (int i = 0; i < array.length; i++) {
            if (i == 0) {
                result += array[i];
            } else {
                result += (connector + array[i]);
            }
        }
        return result;
    }

    public static String[] splitStringArray(String str, String connector) {
        return str.split(connector);
    }

    /**
     * bytes -> HexString
     *
     * @param b
     * @return
     */
    public static String bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }

    /**
     * 16进制转10进制
     *
     * @param hexStr
     * @return
     */
    public static int hexStr2Num(String hexStr) {
        return Integer.parseInt(hexStr, 16);
    }
    /**
     * 16进制转10进制
     *
     * @param hexStr
     * @return
     */
    public static long hexStr2Long(String hexStr) {
        return Long.parseLong(hexStr, 16);
    }

    /**
     * 将数字转换成byteLen字节长度的十六进制数
     *
     * @param num
     * @param byteLen
     * @return
     */
    public static String num2HexStr(int num, int byteLen) {
        String hexNum = Integer.toHexString(num);
        while (hexNum.length() < byteLen * 2) {
            hexNum = "0" + hexNum;
        }
        return hexNum.toUpperCase();
    }

    /**
     * 10进制字符串转16进制字符串
     * @param num
     * @param byteLen
     * @return
     */
    public static  String DexStrToHexStr(String num,int byteLen){
        return num2HexStr(Integer.parseInt(num),byteLen);
    }

    /**
     * 将数字转换成byteLen字节长度的十六进制数
     *
     * @param num
     * @param byteLen
     * @return
     */
    public static String num2HexStr(long num, int byteLen) {
        String hexNum = Long.toHexString(num);
        while (hexNum.length() < byteLen * 2) {
            hexNum = "0" + hexNum;
        }
        return hexNum.toUpperCase();
    }

    /**
     * 16二进制转成2个Hex
     *
     * @param binaryStr
     * @return
     */
    public static String binaryStr2HexStr(String binaryStr) {
        return CodeTool.num2HexStr(Integer.parseInt(binaryStr, 2), 2);
    }

    /**
     * 16二进制转成2个Hex
     *
     * @param binaryStr
     * @return
     */
    public static String binaryStr2HexStr(String binaryStr, int hexLen) {
        return CodeTool.num2HexStr(Integer.parseInt(binaryStr, 2), hexLen);
    }

    /**
     * 任意位16进制数变4位二进制
     *
     * @param hexNum
     * @return
     */
    public static String hexNum2BinaryStr(String hexNum) {
        return hexNum2BinaryStr(hexNum, 4);
    }

    public static String hexNum2BinaryStr(String hexNum, int binaryLenSetted) {
        String result = "";
        char[] chars = hexNum.toCharArray();
        for (char ch : chars) {
            result += singleHexNum2BinaryStrSetLen(ch, binaryLenSetted);
        }
        return result;
    }


    /**
     * 1字节16进制数变8位二进制,不足8位，左边补0.
     *
     * @param hexNum
     * @return
     */
    public static String oneByteHexNum2BinaryStr8(String hexNum) {
        int num = Integer.parseInt(hexNum, 16);
        if (num > 0xFF) {
            AndroidConsoleLogPrinter.e(TAG, "DataTransfer ->oneByteHexNum2BinaryStr8 转换的数据过大");
            return null;
        }
        String binaryString = Integer.toBinaryString(num);
        String leftAddZero = "";
        while ((leftAddZero + binaryString).length() < 8) {
            leftAddZero += "0";
        }
        return leftAddZero + binaryString;
    }

    /**
     * HEX转任意位二进制
     *
     * @param hexNum
     * @param binaryLen
     * @return
     */
    public static String byteHexNum2BinaryStr(String hexNum, int binaryLen) {
        int num = Integer.parseInt(hexNum, 16);
        String binaryString = Integer.toBinaryString(num);
        String leftAddZero = "";
        while ((leftAddZero + binaryString).length() < binaryLen) {
            leftAddZero += "0";
        }
        return leftAddZero + binaryString;
    }

    public static String num2BinaryStr(int num, int binaryLen) {
        String binaryString = Integer.toBinaryString(num);
        String leftAddZero = "";
        while ((leftAddZero + binaryString).length() < binaryLen) {
            leftAddZero += "0";
        }
        return leftAddZero + binaryString;
    }


    /**
     *
     *
     * @param hexNum
     * @param binaryLenSetted 二进制的长度
     * @return
     */
    private static String singleHexNum2BinaryStrSetLen(char hexNum, int binaryLenSetted) {
        String result = "";
        result = Integer.toBinaryString(Integer.parseInt(String.valueOf(hexNum), 16));
        int binaryLen = result.length();
        if (binaryLen < binaryLenSetted) {
            for (int i = binaryLen; i < binaryLenSetted; i++) {
                result = "0" + result;
            }
        }
        return result;
    }


    public static String yihuo(String content) {
        String[] b = hexStr2(content);
        int a = 0;
        for (int i = 0; i < b.length; i++) {
            a = a ^ Integer.parseInt(b[i], 16);
        }
        String result = Integer.toHexString(a);
        if (result.length() == 1) {
            result = "0" + result;
        }
        return result.toUpperCase();
    }


    public static String[] hexStr2(String hexstr) {
        int len = hexstr.length() / 2;
        String[] strs = new String[len];
        for (int i = 0; i < len; i++) {
            try {
                strs[i] = hexstr.substring(i * 2, i * 2 + 2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return strs;
    }

    /**
     * 十进制数转7位二进制字符串,作为低7位。
     *
     * @param num
     * @return
     */
    public static String num2BinaryStr7(int num) {
        return oneByteHexNum2BinaryStr8(Integer.toHexString(num)).substring(1);
    }

    /**
     * 将数字返回为2位的16进制格式的字符串,不足2位前面补0.
     *
     * @param num
     * @return
     */
    public static String num2HexStr(int num) {
        if (num <= 0xFF) {
            return num2HexStr(num, 1);
        } else if (num > 0xFF && num <= 0xFFFF) {
            return num2HexStr(num, 2);
        } else if (num > 0xFFFF && num <= 0xFFFFFF) {
            return num2HexStr(num, 3);
        } else {
//            AndroidConsoleLogPrinter.e(TAG, "转换的数字不可大于0xFFFFFF" );
            return null;
        }
    }

    /**
     * 截取字符串
     *
     * @param resultDecrypt
     * @param params
     * @return
     */
    public static String[] splitStrings(String resultDecrypt, Integer... params) {
        String[] ret = null;
        int fieldLen = params.length;
        ret = new String[fieldLen];
        try {
            int startPos = 0;
            int endPos = 0;
            for (int i = 0; i < fieldLen; i++) {
                endPos = startPos + params[i] * 2;
                ret[i] = resultDecrypt.substring(startPos, endPos);
                startPos = endPos;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static int hex2Int(String hexInt) {
        return Integer.parseInt(hexInt, 16);
    }
    //十六字符串转10进制字符串
    public static String hex2Intstr(String hexInt) {
        try {
            return Integer.parseInt(hexInt, 16)+"";
        }catch (Exception e){
            return hexInt;
        }

    }

    public static long hex2Long(String hexLong) {
        return Long.parseLong(hexLong, 16);
    }

    /**
     * 获取data的所有分包，前提是数据长度大于maxByteLenEachFrame个字节 。
     *
     * @param bigBagHexData
     * @param maxByteLenEachFrame
     * @return
     */
    public static String[] getSmallBagHexData(String bigBagHexData, int maxByteLenEachFrame) {
        //兼容旧的没有分包的情况
        if (bigBagHexData.length() / 2 <= maxByteLenEachFrame) {
            return new String[]{bigBagHexData};
        }

        int total_len = bigBagHexData.length() / 2;
        int bagsCount = (int) Math.ceil(total_len * 1.0 / maxByteLenEachFrame);
        String[] data = new String[bagsCount];
        for (int i = 0; i < bagsCount; i++) {
            int start_index = i * maxByteLenEachFrame * 2;
            int end_index = (i * maxByteLenEachFrame + maxByteLenEachFrame) * 2;
            if (end_index <= bigBagHexData.length()) {
                data[i] = bigBagHexData.substring(start_index, end_index);
            } else {
                data[i] = bigBagHexData.substring(start_index, bigBagHexData.length());
            }
        }
        return data;
    }

    /**
     * 小端模式hex2INT
     *
     * @param hexInt
     * @return
     */
    public static int smallModeHex2Int(String hexInt) {
        String bigHex = "";
        for (int i = hexInt.length() - 2; i >= 0; i -= 2) {
            bigHex += hexInt.substring(i, i + 2);
        }
        return hex2Int(bigHex);
    }


    /**
     * 小端模式hex2INT
     *
     * @param hexLong
     * @return
     */
    public static long smallModeHex2Long(String hexLong) {
        String bigHex = "";
        for (int i = hexLong.length() - 2; i >= 0; i -= 2) {
            bigHex += hexLong.substring(i, i + 2);
        }
        return hex2Long(bigHex);
    }




    public static int yihuo_return_int(String content) {
        String[] b = hexStr2(content);
        int a = 0;
        for (int i = 0; i < b.length; i++) {
            a = a ^ Integer.parseInt(b[i], 16);
        }
        return a;
    }

    /**
     * int转小端模式HEX
     *
     * @param intValue
     * @return
     */
    public static String int2SmallModeHex(int intValue, int byteLen) {
        String bigHex = num2HexStr(intValue, byteLen);
        String smallHex = "";
        for (int i = bigHex.length() - 2; i >= 0; i -= 2) {
            smallHex += bigHex.substring(i, i + 2);
        }
        return smallHex;
    }


    /**
     * long转小端模式HEX
     *
     * @param longValue
     * @return
     */
    public static String long2SmallModeHex(long longValue, int byteLen) {
        String bigHex = num2HexStr(longValue, byteLen);
        String smallHex = "";
        for (int i = bigHex.length() - 2; i >= 0; i -= 2) {
            smallHex += bigHex.substring(i, i + 2);
        }
        return smallHex;
    }


    public static byte[] StringToBytes(String str) {
        int nLen = str.length();
        byte bytes[] = new byte[str.length() / 2];
        for (int i = 0; i < nLen / 2; i++) {
            bytes[i] = StringToByte(str.substring(i * 2, i * 2 + 2));
        }
        return bytes;
    }


    public static byte StringToByte(String str) {
        return (byte) Integer.parseInt(str, 16);
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @return 十六进制char[]
     */
    public static String BytesToString(byte[] inHex, int nOff, int nLen) {
        int i;
        StringBuilder strResult = new StringBuilder();
        strResult.append("");
        for (i = 0; i < nLen; i++) {
            strResult.append(String
                    .valueOf(DIGITS_UPPER[(0xF0 & inHex[nOff + i]) >>> 4]));
            strResult.append(String
                    .valueOf(DIGITS_UPPER[inHex[nOff + i] & 0x0F]));
        }
        return strResult.toString();
    }

    /**
     * 生成随机数
     *
     * @param byteLen 随机数长度
     * @return
     */
    public static String random(int byteLen) {
        String result = "";
        Random random = new Random();
        for (int i = 0; i < byteLen * 2; i++) {
            result += random.nextInt(10);
        }
        return result;
    }


    /**
     * @param chars
     * @return
     */
    public static String everyChar2Hex(String chars) {
        String result = "";
        char[] charArray = chars.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            result += CodeTool.num2HexStr(Integer.parseInt(String.valueOf(charArray[i])), 1);
        }
        return result;
    }


    /**
     * 生成随机数
     *
     * @param byteLen 随机数长度
     * @return 如8个数 12345678，则返回0102**08
     */
    public static String randomEveryChar(int byteLen) {
        String result = "";
        Random random = new Random();
        for (int i = 0; i < byteLen; i++) {
            result += CodeTool.num2HexStr(random.nextInt(10), 1);
        }
        return result;
    }


    /**
     * bcd码转ascii码
     * 即将第一个字符转成其ascii码
     * 如2016121910245520161220   转码后  32303136313231393130323435353230313631323230
     *
     * @param bcd
     * @return
     */
    public static String bcd2AsciiHex(String bcd) {
        String result = "";
        char[] chars = bcd.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            result += bcd2AsciiHex(chars[i]);
        }
        return result;
    }

    /**
     * 单个字符转ascii码
     *
     * @param ch
     * @return
     */
    public static String bcd2AsciiHex(char ch) {
        return num2HexStr((int) ch, 1);
    }

    public static char ascii2Char(String ascii) {
        return (char) CodeTool.hex2Int(ascii);
    }


    public static String ascii2Bcd(String ascii) {
        String result = "";
        for (int i = 0; i < ascii.length(); i += 2) {
            String substring = ascii.substring(i, i + 2);
            result += ascii2Char(substring);
        }
        return result;
    }


    /**
     * 切割字符串
     * 将hex按照每lengthOfByte个字节来切割。
     */
    public static List<String> cutStr2Array(String hex, int lengthOfByte) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < Math.ceil(hex.length() * 1.0 / 2 / lengthOfByte); i++) {
            if ((i + 1) * lengthOfByte * 2 < hex.length()) {
                result.add(hex.substring(i * lengthOfByte * 2, (i + 1) * lengthOfByte * 2));
            } else {
                result.add(hex.substring(i * lengthOfByte * 2, hex.length()));
            }
        }
        return result;
    }

    /**
     * 多个16进制数字转多个10进制数字
     * @param hexs 16进制数字

     * @return
     */
    public static String HexsToInts(String hexs){
        byte[] bytes = StringToBytes(hexs);
        String str ="";
        for(int i = 0 ;i < bytes.length ;i++){
            str = str+bytes[i];
        }
        return str;
    }

    /**
     *
     * @param inData
     * @param len
     * @param initVal
     * @return
     */
    public static char getCRC16(byte inData[], int len, char initVal) {
        char crcbak;
        int i;

        crcbak = initVal;

        for (i = 0; i < len; ++i)
        {
            crcbak = (char) ((crcbak >> 8) ^ (CRC_TABLE_8408[(crcbak ^ inData[i]) & 0xFF]));
        }

        crcbak = (char) ~crcbak;

        return crcbak;
    }

/*

    public static char  getCRC16FromGZD(byte inData[], short len)
    {
        short crc = 0;
        char da = 0;

        crc = 0;
        int array_index = 0;
        while(len-- != 0)
        {
            da = (char)(crc / 256);// 以8位二进制数的形式暂存CRC的高8位
            crc <<= 8;        // 左移8位,相当于CRC的低8位乘以28
            crc ^= CRC_TABLE_8408[ da ^ inData[array_index]]; // 高8位和当前字节相加后再查表求CRC,再加上以前的CRC
            array_index++;
        }
        return (char)(crc);
    }

    public static char  getCRC16FromGZD(int[] inData, short len)
    {
        int crc = 0;
        int da = 0;

        int array_index = 0;
        while(len-- != 0)
        {
            da =  (crc / 256);// 以8位二进制数的形式暂存CRC的高8位
            crc <<= 8;        // 左移8位,相当于CRC的低8位乘以28
            crc ^= CRC_TABLE_8408[ da ^ inData[array_index]]; // 高8位和当前字节相加后再查表求CRC,再加上以前的CRC
            array_index++;
        }
        return (char)(crc);
    }



    public static char getCRC16(int[] inData, int len, char initVal) {
        return getCRC16FromGZD(inData, (short) len);
    }

*/

    public static float convertDouble2Float(double value){
        return Float.valueOf(String.valueOf(value));
    }

    public static String getNiceStrFromInt(int value){
        String s = String.valueOf(value);
        if(s.length() < 2){
            return "0" + s;
        }else{
            return s;
        }
    }
}